import request from '@/utils/request'

/**
 * 天气API服务
 * 使用多个免费天气API作为备选方案
 */

// 免费天气API配置
const WEATHER_APIS = {
  // OpenWeatherMap (免费版：1000次/天)
  openweather: {
    baseUrl: 'https://api.openweathermap.org/data/2.5/weather',
    apiKey: 'c951ef71bea29e0c7661f5072a5709e1', // 需要注册获取
    params: {
      appid: 'your_openweather_api_key',
      units: 'metric',
      lang: 'zh_cn'
    }
  },
  
  // 和风天气 (免费版：1000次/天)
  qweather: {
    baseUrl: 'https://devapi.qweather.com/v7/weather/now',
    apiKey: 'n34qbj9u9p.re.qweatherapi.com', // 需要注册获取
    params: {
      key: 'n34qbj9u9p.re.qweatherapi.com'
    }
  },
  
  // 心知天气 (免费版：1000次/月)
  thinkpage: {
    baseUrl: 'https://api.thinkpage.cn/v3/weather/now.json',
    apiKey: 'SMoMa2KLrXt05TZt0', // 需要注册获取
    params: {
      key: 'SMoMa2KLrXt05TZt0',
      location: '',
      language: 'zh-Hans',
      unit: 'c'
    }
  }
}

/**
 * 获取天气信息
 * @param {string} location 城市名称
 * @returns {Promise<Object>} 天气信息
 */
export async function getWeatherInfo(location) {
  try {
    // 优先使用真实API
    return await getRealWeatherData(location)
  } catch (error) {
    console.error('获取天气信息失败:', error)
    // 如果真实API失败，使用模拟数据
    return await getMockWeatherData(location)
  }
}

/**
 * 获取真实天气数据
 * @param {string} location 城市名称
 * @returns {Promise<Object>} 天气信息
 */
async function getRealWeatherData(location) {
  try {
    // 导入全国地区代码数据
    const chinaRegions = await import('./china-regions.json')
    const cityInfo = findCityInfo(chinaRegions.default, location)
    
    if (!cityInfo) {
      throw new Error(`未找到城市 ${location} 的代码信息`)
    }
    
    // 尝试使用和风天气API
    try {
      return await getQWeatherData(cityInfo)
    } catch (error) {
      console.warn('和风天气API调用失败，尝试心知天气API:', error)
      // 如果和风天气失败，尝试心知天气
      return await getThinkPageWeatherData(cityInfo)
    }
  } catch (error) {
    console.error('获取真实天气数据失败:', error)
    throw error
  }
}

/**
 * 递归查找城市信息
 * @param {Object} regions 地区数据
 * @param {string} location 城市名称
 * @returns {Object|null} 城市信息
 */
function findCityInfo(regions, location) {
  for (const [key, region] of Object.entries(regions)) {
    if (key === location) {
      return {
        code: region.code,
        name: region.name,
        lat: region.lat || '39.9042',
        lon: region.lon || '116.4074'
      }
    }
    
    if (region.children) {
      const found = findCityInfo(region.children, location)
      if (found) {
        return found
      }
    }
  }
  return null
}

/**
 * 使用和风天气API获取天气数据
 * @param {Object} cityInfo 城市信息
 * @returns {Promise<Object>} 天气信息
 */
async function getQWeatherData(cityInfo) {
  const { baseUrl, apiKey } = WEATHER_APIS.qweather
  const url = `${baseUrl}?location=${cityInfo.code}&key=${apiKey}`
  
  const response = await fetch(url)
  if (!response.ok) {
    throw new Error(`和风天气API调用失败: ${response.status}`)
  }
  
  const data = await response.json()
  
  if (data.code !== '200') {
    throw new Error(`和风天气API返回错误: ${data.code}`)
  }
  
  const now = data.now
  return {
    temperature: now.temp,
    location: cityInfo.name,
    description: now.text,
    wind: `${now.windDir}${now.windScale}级`,
    humidity: now.humidity,
    icon: getWeatherIcon(now.text),
    apiSource: '和风天气'
  }
}

/**
 * 使用心知天气API获取天气数据
 * @param {Object} cityInfo 城市信息
 * @returns {Promise<Object>} 天气信息
 */
async function getThinkPageWeatherData(cityInfo) {
  const { baseUrl, apiKey } = WEATHER_APIS.thinkpage
  const url = `${baseUrl}?key=${apiKey}&location=${cityInfo.lat},${cityInfo.lon}&language=zh-Hans&unit=c`
  
  const response = await fetch(url)
  if (!response.ok) {
    throw new Error(`心知天气API调用失败: ${response.status}`)
  }
  
  const data = await response.json()
  
  if (data.status !== 'OK') {
    throw new Error(`心知天气API返回错误: ${data.status}`)
  }
  
  const now = data.results[0].now
  return {
    temperature: now.temperature,
    location: cityInfo.name,
    description: now.text,
    wind: `${now.wind_direction}${now.wind_scale}级`,
    humidity: now.humidity,
    icon: getWeatherIcon(now.text),
    apiSource: '心知天气'
  }
}

/**
 * 获取模拟天气数据
 * @param {string} location 城市名称
 * @returns {Promise<Object>} 天气信息
 */
async function getMockWeatherData(location) {
  // 模拟API延迟
  await new Promise(resolve => setTimeout(resolve, 500))
  
  const weatherData = {
    '北京市': {
      temperature: '15',
      location: '北京市',
      description: '晴',
      wind: '微风',
      humidity: '45',
      icon: 'el-icon-sunny'
    },
    '上海市': {
      temperature: '18',
      location: '上海市',
      description: '多云',
      wind: '东南风2级',
      humidity: '60',
      icon: 'el-icon-cloudy'
    },
    '广州市': {
      temperature: '25',
      location: '广州市',
      description: '小雨',
      wind: '南风3级',
      humidity: '80',
      icon: 'el-icon-rainy'
    },
    '深圳市': {
      temperature: '26',
      location: '深圳市',
      description: '晴转多云',
      wind: '南风2级',
      humidity: '70',
      icon: 'el-icon-partly-cloudy'
    },
    '珠海市': {
      temperature: '24',
      location: '珠海市',
      description: '多云',
      wind: '东南风3级',
      humidity: '75',
      icon: 'el-icon-cloudy'
    },
    '南京市': {
      temperature: '16',
      location: '南京市',
      description: '晴',
      wind: '西北风2级',
      humidity: '55',
      icon: 'el-icon-sunny'
    },
    '苏州市': {
      temperature: '17',
      location: '苏州市',
      description: '多云转晴',
      wind: '东风2级',
      humidity: '60',
      icon: 'el-icon-partly-cloudy'
    },
    '无锡市': {
      temperature: '16',
      location: '无锡市',
      description: '晴',
      wind: '东南风1级',
      humidity: '58',
      icon: 'el-icon-sunny'
    },
    '杭州市': {
      temperature: '19',
      location: '杭州市',
      description: '小雨',
      wind: '南风2级',
      humidity: '85',
      icon: 'el-icon-rainy'
    },
    '宁波市': {
      temperature: '18',
      location: '宁波市',
      description: '多云',
      wind: '东南风3级',
      humidity: '70',
      icon: 'el-icon-cloudy'
    },
    '温州市': {
      temperature: '20',
      location: '温州市',
      description: '小雨转多云',
      wind: '南风2级',
      humidity: '80',
      icon: 'el-icon-partly-cloudy'
    }
  }
  
  return weatherData[location] || getDefaultWeatherData(location)
}

/**
 * 获取默认天气数据
 * @param {string} location 城市名称
 * @returns {Object} 默认天气信息
 */
function getDefaultWeatherData(location) {
  return {
    temperature: '20',
    location: location,
    description: '晴',
    wind: '微风',
    humidity: '50',
    icon: 'el-icon-sunny'
  }
}

/**
 * 根据天气状况获取图标
 * @param {string} description 天气描述
 * @returns {string} 图标类名
 */
export function getWeatherIcon(description) {
  const iconMap = {
    '晴': 'el-icon-sunny',
    '多云': 'el-icon-cloudy',
    '阴': 'el-icon-cloudy',
    '小雨': 'el-icon-rainy',
    '中雨': 'el-icon-rainy',
    '大雨': 'el-icon-rainy',
    '暴雨': 'el-icon-rainy',
    '雪': 'el-icon-snowy',
    '雾': 'el-icon-foggy',
    '霾': 'el-icon-foggy'
  }
  
  for (const [key, icon] of Object.entries(iconMap)) {
    if (description.includes(key)) {
      return icon
    }
  }
  
  return 'el-icon-sunny'
}

/**
 * 推荐的免费天气API
 */
export const RECOMMENDED_APIS = {
  // 1. OpenWeatherMap (推荐)
  openweather: {
    name: 'OpenWeatherMap',
    url: 'https://openweathermap.org/api',
    freeLimit: '1000次/天',
    features: ['全球天气', '多语言支持', '历史数据'],
    setup: '注册账号 → 获取API Key → 配置到代码中'
  },
  
  // 2. 和风天气 (国内推荐)
  qweather: {
    name: '和风天气',
    url: 'https://dev.qweather.com/',
    freeLimit: '1000次/天',
    features: ['国内天气', '中文支持', '实时数据'],
    setup: '注册账号 → 获取API Key → 配置到代码中'
  },
  
  // 3. 心知天气
  thinkpage: {
    name: '心知天气',
    url: 'https://www.thinkpage.cn/',
    freeLimit: '1000次/月',
    features: ['全球天气', '中文支持', '简单易用'],
    setup: '注册账号 → 获取API Key → 配置到代码中'
  },
  
  // 4. 高德天气API
  amap: {
    name: '高德天气',
    url: 'https://lbs.amap.com/api/webservice/guide/api/weatherinfo',
    freeLimit: '3000次/天',
    features: ['国内天气', '高德地图集成', '免费额度大'],
    setup: '注册高德开发者账号 → 获取API Key → 配置到代码中'
  }
}
